<template>
  <div class="container">
    <a-card class="general-card">
      <!-- 搜索区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="角色名称">
                  <a-input
                    v-model="searchForm.roleName"
                    placeholder="请输入角色名称"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
            <a-button @click="resetForm">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 工具栏 -->
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="roleId"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #action="{ record }">
          <a-space>
            <a-button
              v-if="record.roleId !== 1"
              type="text"
              size="small"
              @click="handleEdit(record)"
              >编辑</a-button
            >
            <a-button
              v-if="record.roleId !== 1"
              type="text"
              size="small"
              status="danger"
              @click="handleDelete(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 弹窗：角色表单 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      :width="380"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
        class="role-modal-form"
      >
        <a-form-item field="roleName" label="角色名称" required>
          <a-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item field="roleLevel" label="角色级别" required>
          <a-select v-model="formData.roleLevel" placeholder="请选择级别">
            <a-option :value="1">一级</a-option>
            <a-option :value="2">二级</a-option>
            <a-option :value="3">三级</a-option>
            <a-option :value="4">四级</a-option>
            <a-option :value="5">五级</a-option>
            <a-option :value="6">六级</a-option>
            <a-option :value="7">七级</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="funcList" label="菜单权限">
          <div class="menu-tree-container">
            <a-tree
              v-model:checked-keys="checkedMenuKeys"
              v-model:expanded-keys="expandedKeys"
              :data="menuTreeData"
              :checkable="true"
              :check-strictly="false"
              :field-names="{
                key: 'funcId',
                title: 'funcName',
                children: 'children',
              }"
              @check="onMenuCheck"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  getRoleList,
  createRole,
  updateRole,
  deleteRole,
  getRoleById,
  getAllMenus,
  type RoleInfo,
  type RoleQueryParams,
  type MenuTreeNode,
} from "@/api/role";

// 响应式数据
const loading = ref(false);
const tableData = ref<RoleInfo[]>([]);
const formVisible = ref(false);
const formTitle = ref("新增角色");
const formRef = ref();

// 菜单树相关数据
const menuTreeData = ref<MenuTreeNode[]>([]);
const checkedMenuKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]); // 控制菜单树展开状态

// 搜索表单
const searchForm = reactive<RoleQueryParams>({
  pageNo: 1,
  pageSize: 10,
  roleName: "",
  roleLevel: undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 表单数据
const formData = reactive<RoleInfo>({
  roleName: "",
  roleLevel: 1,
});

// 表单验证规则
const formRules = {
  roleName: [{ required: true, message: "请输入角色名称" }],
  roleLevel: [{ required: true, message: "请选择角色级别" }],
};

// 角色级别选项
const roleLevelOptions = [
  { label: "一级", value: 1 },
  { label: "二级", value: 2 },
  { label: "三级", value: 3 },
  { label: "四级", value: 4 },
  { label: "五级", value: 5 },
  { label: "六级", value: 6 },
  { label: "七级", value: 7 },
];

// 表格列配置
const columns = [
  { title: "角色ID", dataIndex: "roleId" },
  { title: "角色名称", dataIndex: "roleName" },
  {
    title: "角色级别",
    dataIndex: "roleLevel",
    render: ({ record }) => {
      const level = roleLevelOptions.find((l) => l.value === record.roleLevel);
      return level ? level.label : "管理员";
    },
  },
  {
    title: "操作",
    fixed: "right",
    slotName: "action",
  },
];

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true;
  try {
    const params: RoleQueryParams = {
      ...searchForm,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    };

    const response = await getRoleList(params);

    if (response.code === 200 || response.code === 0) {
      tableData.value = response.data.rows;
      pagination.total = response.data.page.totalRow;
    } else {
      Message.error(response.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表错误:", error);
    Message.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp?: number) => {
  if (!timestamp) return "-";
  return new Date(timestamp).toLocaleString();
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchRoleList();
};

// 重置搜索
const resetForm = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : "";
  });
  pagination.current = 1;
  fetchRoleList();
};

// 分页变化
const onPageChange = (page: number) => {
  pagination.current = page;
  fetchRoleList();
};

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  searchForm.pageSize = pageSize;
  pagination.current = 1;
  fetchRoleList();
};

// 新增角色
const handleAdd = async () => {
  formTitle.value = "新增角色";

  // 重置表单数据
  Object.assign(formData, {
    roleName: "",
    roleLevel: 1,
  });

  // 清空菜单选择和展开状态
  checkedMenuKeys.value = [];
  expandedKeys.value = [];

  formVisible.value = true;
};

// 编辑角色
const handleEdit = async (record: RoleInfo) => {
  formTitle.value = "编辑角色";

  try {
    // 获取角色详细信息
    const roleResponse = await getRoleById(record.roleId!);
    if (roleResponse.code === 200 || roleResponse.code === 0) {
      Object.assign(formData, roleResponse.data);

      // 设置菜单权限 - 确保是字符串数组
      if (
        roleResponse.data.funcList &&
        Array.isArray(roleResponse.data.funcList)
      ) {
        checkedMenuKeys.value = roleResponse.data.funcList.map((id) =>
          String(id)
        );
      } else {
        checkedMenuKeys.value = [];
      }

      // 重置展开状态
      expandedKeys.value = [];
    } else {
      Message.error(roleResponse.message || "获取角色信息失败");
      return;
    }

    formVisible.value = true;
  } catch (error) {
    console.error("获取角色信息错误:", error);
    Message.error("获取角色信息失败");
  }
};

// 删除角色
const handleDelete = (record: RoleInfo) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除角色 "${record.roleName}" 吗？`,
    onOk: async () => {
      try {
        const response = await deleteRole(record.roleId!);
        if (response.code === 200 || response.code === 0) {
          Message.success("删除成功");
          fetchRoleList();
        } else {
          Message.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除角色错误:", error);
        Message.error("删除失败");
      }
    },
  });
};

// 获取所有菜单
const fetchAllMenus = async () => {
  try {
    const response = await getAllMenus();
    if (response.code === 200 || response.code === 0) {
      menuTreeData.value = response.data;
      console.log("菜单数据加载成功:", response.data);
    } else {
      Message.error(response.message || "获取菜单列表失败");
    }
  } catch (error) {
    console.error("获取菜单列表错误:", error);
    Message.error("获取菜单列表失败");
  }
};

// 菜单选择变化
const onMenuCheck = (checkedKeys: string[]) => {
  checkedMenuKeys.value = checkedKeys;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    // 准备提交数据，包含菜单权限 - 保持字符串格式
    const submitData = {
      ...formData,
      funcList: checkedMenuKeys.value,
    };

    if (formTitle.value === "新增角色") {
      const response = await createRole(submitData);
      if (response.code === 200 || response.code === 0) {
        Message.success("新增成功");
        formVisible.value = false;
        fetchRoleList();
      } else {
        Message.error(response.message || "新增失败");
      }
    } else {
      const response = await updateRole(submitData);
      if (response.code === 200 || response.code === 0) {
        Message.success("更新成功");
        formVisible.value = false;
        fetchRoleList();
      } else {
        Message.error(response.message || "更新失败");
      }
    }
  } catch (error) {
    console.error("提交表单错误:", error);
    Message.error("操作失败");
  }
};

// 取消表单
const handleCancel = () => {
  formVisible.value = false;
  // 重置展开状态
  expandedKeys.value = [];
};

// 页面加载时获取数据
onMounted(async () => {
  // 同时获取角色列表和菜单数据
  await Promise.all([fetchRoleList(), fetchAllMenus()]);
});
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
}

.role-modal-form :deep(.arco-form-item-content) {
  width: 350px !important;
  min-width: 0 !important;
  max-width: 350px !important;
}
.role-modal-form :deep(.arco-input-wrapper),
.role-modal-form :deep(.arco-input),
.role-modal-form :deep(.arco-select-view-single) {
  width: 350px !important;
  min-width: 0 !important;
  max-width: 350px !important;
  box-sizing: border-box;
}
.role-modal-form .menu-tree-container {
  width: 350px;
  max-width: 350px;
  min-width: 350px;
  max-height: 350px;
  min-height: 200px;
  overflow-y: auto;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  padding: 0;
  background-color: var(--color-bg-2);
  box-sizing: border-box;
}
</style>
